package com.beiding.workordersystem.main.controller;

import com.beiding.workordersystem.common.standard.R;
import com.beiding.workordersystem.main.entity.Option;
import com.beiding.workordersystem.main.option.OptionAble;
import com.beiding.workordersystem.main.option.TreeAble;
import com.beiding.workordersystem.main.service.OptionService;
import com.beiding.workordersystem.main.utils.OptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/settings")
public class OptionController {

    @Autowired
    private OptionService optionService;

    @PostMapping("/{type}/save")
    R save(@PathVariable String type, @RequestBody Map<String, Object> body) throws ClassNotFoundException {
        Class<? extends OptionAble> aClass = (Class<? extends OptionAble>) Class.forName("com.beiding.workordersystem.main.option." + type);

        //将值首先映射成实体
        Option option = OptionUtils.mapToOption(body, aClass);

        //执行保存操作
        optionService.save(option);
        return R.ok(option.getId());
    }

    @GetMapping("/{type}/tree")
    R tree(@PathVariable String type) throws ClassNotFoundException {
        Class<? extends TreeAble> aClass = (Class<? extends TreeAble>) Class.forName("com.beiding.workordersystem.main.option." + type);
        return R.ok(optionService.tree(aClass));
    }

    @PostMapping("/delete")
    R delete(@RequestBody String[] ids) {
        optionService.delete(ids);
        return R.ok();
    }

    @GetMapping("/{type}/list")
    R list(@PathVariable String type) throws ClassNotFoundException {
        Class<?> aClass = Class.forName("com.beiding.workordersystem.main.option." + type);
        return R.ok(optionService.list(aClass));
    }

}
